package com.js.common.core;

import net.mamoe.mirai.Bot;
import net.mamoe.mirai.BotFactory;
import net.mamoe.mirai.event.events.FriendMessageEvent;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.utils.BotConfiguration;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@Component
public class BotRunner implements ApplicationRunner {

    @Resource
    private ApplicationContext applicationContext;
    private long qq = 2754447043L;
    private String password = "Jsynzzp123";

    @Override
    public void run(ApplicationArguments args) {
        // 使用自定义配置
        Bot bot = BotFactory.INSTANCE.newBot(qq, password, new BotConfiguration() {{
            fileBasedDeviceInfo(); // 使用 device.json 存储设备信息
            setProtocol(MiraiProtocol.ANDROID_PAD); // 切换协议
        }});
        bot.login();
        bot.getEventChannel().subscribeAlways(GroupMessageEvent.class, (event) -> {
            Map<String, BotHandler> serviceMap = applicationContext.getBeansOfType(BotHandler.class);
            for (BotHandler service : serviceMap.values()) {
                service.setEvent(event);
                service.setGroup(event);
                try {
                    service.handler(event.getSender().getId(), event.getSubject().getId(), event.getMessage());
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        bot.getEventChannel().subscribeAlways(FriendMessageEvent.class, (event) -> {
            Map<String, BotHandler> serviceMap = applicationContext.getBeansOfType(BotHandler.class);
            for (BotHandler service : serviceMap.values()) {
                service.setEvent(event);
                service.setFriend(event);
                try {
                    service.handler(event.getSender().getId(), event.getSubject().getId(), event.getMessage());
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}
